/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import static com.railway.app.NewStaffPanel.isNumeric;
import static com.railway.app.NewStaffPanel.isValidEmailAddress;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;

import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author Kenny
 */
public class ModifyStaffPanel extends javax.swing.JPanel {

    Image imgArrow = new ImageIcon(this.getClass().getResource("/com/railway/image/arrow.png")).getImage();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    private JFileChooser chooser,jfcImageChooser;
    private FileNameExtensionFilter filter;
    private File image;
    private ImageIcon photo;
    private Image scaleImage;
    private Map<String, Object> data = new HashMap<>();
    /**
     * Creates new form RoutePanel
     */
    public ModifyStaffPanel() {
        initComponents();
        disableAll();
        setDefault();
        jcbIC.setSelected(true);
    }

        
    public void disableAll(){
        jtfICID.setEditable(true);
        jtfFirstName.setEditable(false);
        jtfLastName.setEditable(false);
        jtfDoB.setEnabled(false);
        jrbMale.setEnabled(false);
        jrbFemale.setEnabled(false);
        jcbPosition.setEnabled(false);
        jtfPhoneNo.setEditable(false);
        jtfEmail.setEditable(false);
        jtfAddress.setEditable(false);
        jtfCity.setEditable(false);
        jtfState.setEditable(false);
        jtfPostalCode.setEditable(false);
        jcbQuestion.setEnabled(false);
        jtfAnswer.setEditable(false);
        jbtUpdate.setEnabled(false);
        jYearEmployedChooser.setEnabled(false);
        jYearEmployedChooser.setYear(2013);
        
    }
    
    public void enableAll(){
        jtfICID.setEditable(true);
        jtfFirstName.setEditable(true);
        jtfLastName.setEditable(true);
        jtfDoB.setEnabled(true);
        jrbMale.setEnabled(true);
        jrbFemale.setEnabled(true);
        jcbPosition.setEnabled(true);
        jtfPhoneNo.setEditable(true);
        jtfEmail.setEditable(true);
        jtfAddress.setEditable(true);
        jtfCity.setEditable(true);
        jtfState.setEditable(true);
        jtfPostalCode.setEditable(true);
        jcbQuestion.setEnabled(true);
        jtfAnswer.setEditable(true);
        jYearEmployedChooser.setEnabled(true);
        jbtUpdate.setEnabled(true);
    }
    
    public void setDefault(){
        jtfFirstName.setText(null);
        jtfLastName.setText(null);
        jtfDoB.setDate(null);
        jcbPosition.setSelectedIndex(0);
        jtfPhoneNo.setText(null);
        jtfEmail.setText(null);
        jtfAddress.setText(null);
        jtfCity.setText(null);
        jtfState.setText(null);
        jtfPostalCode.setText(null);
        jcbQuestion.setSelectedIndex(0);
        jtfAnswer.setText(null);
        jbtUpdate.setEnabled(false);
        jYearEmployedChooser.setEnabled(false);
    }
    
    public static boolean isNumeric(String str){  
        try{  
            double d = Double.parseDouble(str);  
        }  
        catch(NumberFormatException nfe){  
            return false;  
        }  
        return true;  
    }
    
    private ImageIcon getImageFile(String url, boolean isUrl) {
        Image img;
        BufferedImage bfImg = null;
        try {
            if (isUrl) {
                String serverurl = "http://localhost/RailwayWeb/";
                img = new ImageIcon(new URL(serverurl + url)).getImage();
            } else {
                img = ImageIO.read(new File(url));
            }
            bfImg = new BufferedImage(jlblImage.getWidth(), jlblImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = bfImg.createGraphics();
            g2d.drawImage(img, 0, 0, jlblImage.getWidth(), jlblImage.getHeight(), this);
            g2d.dispose();
        } catch (MalformedURLException ex) {
            Logger.getLogger(PointRedemptionPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PointRedemptionPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new ImageIcon(bfImg);
    }

    private void generateByteDataFromImageFile(File file) {
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, file.getName().substring(file.getName().lastIndexOf(".") + 1), baos);
            byte[] imageByte = baos.toByteArray();
            String encoded = Base64.encodeBase64String(imageByte);
            data.put("imagedata", encoded);
            data.put("imagename", file.getName());
        } catch (IOException | IllegalArgumentException ex) {
            Toast.makeText(this, "This is not a valid image file.", Toast.LENGTH_SHORT).display();
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgIndex = new javax.swing.ButtonGroup();
        bgGender = new javax.swing.ButtonGroup();
        jpRoute = new javax.swing.JPanel();
        jpStaffParticular = new javax.swing.JPanel();
        jlblFirstName = new javax.swing.JLabel();
        jlblLastName = new javax.swing.JLabel();
        jtfLastName = new javax.swing.JTextField();
        jlblGender = new javax.swing.JLabel();
        jrbMale = new javax.swing.JRadioButton();
        jrbFemale = new javax.swing.JRadioButton();
        jlblPosition = new javax.swing.JLabel();
        jcbPosition = new javax.swing.JComboBox();
        jlblDoB = new javax.swing.JLabel();
        jtfICID = new javax.swing.JTextField();
        jtfFirstName = new javax.swing.JTextField();
        jbSearch = new javax.swing.JButton();
        jcbIC = new javax.swing.JCheckBox();
        jcbID = new javax.swing.JCheckBox();
        jlblYearEmployed = new javax.swing.JLabel();
        jYearEmployedChooser = new com.toedter.calendar.JYearChooser();
        jtfDoB = new com.toedter.calendar.JDateChooser();
        jpAddress = new javax.swing.JPanel();
        jlblAddress = new javax.swing.JLabel();
        jlblCity = new javax.swing.JLabel();
        jlblState = new javax.swing.JLabel();
        jlblPostalCode = new javax.swing.JLabel();
        jtfCity = new javax.swing.JTextField();
        jtfState = new javax.swing.JTextField();
        jtfPostalCode = new javax.swing.JTextField();
        jtfAddress = new javax.swing.JTextField();
        jlblImage = new javax.swing.JLabel();
        jbtBrowse = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jpSecurity = new javax.swing.JPanel();
        jlblQuestion = new javax.swing.JLabel();
        jlblAnswer = new javax.swing.JLabel();
        jcbQuestion = new javax.swing.JComboBox();
        jtfAnswer = new javax.swing.JTextField();
        jpContacts = new javax.swing.JPanel();
        jlblPhoneNo = new javax.swing.JLabel();
        jlblEmail = new javax.swing.JLabel();
        jtfPhoneNo = new javax.swing.JTextField();
        jtfEmail = new javax.swing.JTextField();
        jbtUpdate = new javax.swing.JButton();
        jpRouteArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), getHeight(), this);
            }
        };

        bgIndex.add(jcbIC);
        bgIndex.add(jcbID);

        bgGender.add(jrbMale);
        bgGender.add(jrbFemale);

        setPreferredSize(new java.awt.Dimension(870, 460));
        setLayout(null);

        jpRoute.setBackground(new java.awt.Color(220, 220, 220));
        jpRoute.setLayout(null);

        jpStaffParticular.setBorder(javax.swing.BorderFactory.createTitledBorder("Staff Particular"));

        jlblFirstName.setText("First Name");

        jlblLastName.setText("Last Name");

        jlblGender.setText("Gender");

        jrbMale.setText("Male");

        jrbFemale.setText("Female");

        jlblPosition.setText("Position");

        jcbPosition.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Admin", "Staff" }));

        jlblDoB.setText("DoB");

        jbSearch.setText("Search");
        jbSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSearchActionPerformed(evt);
            }
        });

        jcbIC.setText("IC");
        jcbIC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbICActionPerformed(evt);
            }
        });

        jcbID.setText("ID");
        jcbID.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbIDActionPerformed(evt);
            }
        });

        jlblYearEmployed.setText("Year Employed");

        jtfDoB.setDateFormatString("yyyy-MM-dd");

        javax.swing.GroupLayout jpStaffParticularLayout = new javax.swing.GroupLayout(jpStaffParticular);
        jpStaffParticular.setLayout(jpStaffParticularLayout);
        jpStaffParticularLayout.setHorizontalGroup(
            jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpStaffParticularLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jlblYearEmployed, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpStaffParticularLayout.createSequentialGroup()
                        .addComponent(jcbIC, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbID, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jlblPosition, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlblGender, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlblDoB, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlblLastName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jlblFirstName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpStaffParticularLayout.createSequentialGroup()
                        .addGap(18, 18, Short.MAX_VALUE)
                        .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpStaffParticularLayout.createSequentialGroup()
                                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jtfICID, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jtfFirstName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jtfLastName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jbSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpStaffParticularLayout.createSequentialGroup()
                                    .addComponent(jrbMale, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jrbFemale, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addComponent(jcbPosition, javax.swing.GroupLayout.Alignment.LEADING, 0, 168, Short.MAX_VALUE))
                            .addComponent(jtfDoB, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jpStaffParticularLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jYearEmployedChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jpStaffParticularLayout.setVerticalGroup(
            jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpStaffParticularLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jtfICID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbSearch))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jcbIC)
                        .addComponent(jcbID)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblFirstName)
                    .addComponent(jtfFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblLastName)
                    .addComponent(jtfLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlblDoB)
                    .addComponent(jtfDoB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblGender)
                    .addComponent(jrbMale)
                    .addComponent(jrbFemale))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblPosition)
                    .addComponent(jcbPosition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpStaffParticularLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlblYearEmployed)
                    .addComponent(jYearEmployedChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jpRoute.add(jpStaffParticular);
        jpStaffParticular.setBounds(10, 10, 410, 260);

        jpAddress.setBorder(javax.swing.BorderFactory.createTitledBorder("Address"));

        jlblAddress.setText("Address");

        jlblCity.setText("City");

        jlblState.setText("State");

        jlblPostalCode.setText("Postal Code");

        jbtBrowse.setText("Browse");
        jbtBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtBrowseActionPerformed(evt);
            }
        });

        jLabel3.setText("Picture");

        javax.swing.GroupLayout jpAddressLayout = new javax.swing.GroupLayout(jpAddress);
        jpAddress.setLayout(jpAddressLayout);
        jpAddressLayout.setHorizontalGroup(
            jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAddressLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jlblAddress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jlblCity, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jlblState, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jlblPostalCode, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE))
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpAddressLayout.createSequentialGroup()
                        .addComponent(jlblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 167, Short.MAX_VALUE)
                        .addComponent(jbtBrowse))
                    .addGroup(jpAddressLayout.createSequentialGroup()
                        .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jtfState, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
                                .addComponent(jtfCity, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jtfPostalCode, javax.swing.GroupLayout.Alignment.LEADING))
                            .addComponent(jtfAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jpAddressLayout.setVerticalGroup(
            jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAddressLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblAddress)
                    .addComponent(jtfAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblCity)
                    .addComponent(jtfCity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblState)
                    .addComponent(jtfState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblPostalCode)
                    .addComponent(jtfPostalCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpAddressLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbtBrowse))
                    .addGroup(jpAddressLayout.createSequentialGroup()
                        .addGroup(jpAddressLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(0, 11, Short.MAX_VALUE))))
        );

        jpRoute.add(jpAddress);
        jpAddress.setBounds(430, 10, 430, 260);

        jpSecurity.setBorder(javax.swing.BorderFactory.createTitledBorder("Security"));

        jlblQuestion.setText("Question");

        jlblAnswer.setText("Answer");

        jcbQuestion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "What was your childhood nickname?", "What street did you live on in third grade?", "In what city or town did your mother and father meet?", "What was the last name of your third grade teacher?", "What time of the day were you born?", "In what city or town was your first job?", "What was your favorite place to visit as a child?" }));

        javax.swing.GroupLayout jpSecurityLayout = new javax.swing.GroupLayout(jpSecurity);
        jpSecurity.setLayout(jpSecurityLayout);
        jpSecurityLayout.setHorizontalGroup(
            jpSecurityLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpSecurityLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpSecurityLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jlblQuestion, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                    .addComponent(jlblAnswer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jpSecurityLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jcbQuestion, 0, 251, Short.MAX_VALUE)
                    .addComponent(jtfAnswer))
                .addContainerGap(78, Short.MAX_VALUE))
        );
        jpSecurityLayout.setVerticalGroup(
            jpSecurityLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpSecurityLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpSecurityLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblQuestion)
                    .addComponent(jcbQuestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpSecurityLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblAnswer)
                    .addComponent(jtfAnswer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        jpRoute.add(jpSecurity);
        jpSecurity.setBounds(430, 280, 430, 120);

        jpContacts.setBorder(javax.swing.BorderFactory.createTitledBorder("Contacts"));

        jlblPhoneNo.setText("Phone No");

        jlblEmail.setText("Email");

        javax.swing.GroupLayout jpContactsLayout = new javax.swing.GroupLayout(jpContacts);
        jpContacts.setLayout(jpContactsLayout);
        jpContactsLayout.setHorizontalGroup(
            jpContactsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpContactsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpContactsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jlblPhoneNo, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
                    .addComponent(jlblEmail, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jpContactsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtfEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfPhoneNo, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(121, Short.MAX_VALUE))
        );
        jpContactsLayout.setVerticalGroup(
            jpContactsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpContactsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpContactsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblPhoneNo)
                    .addComponent(jtfPhoneNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpContactsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblEmail)
                    .addComponent(jtfEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(45, Short.MAX_VALUE))
        );

        jpRoute.add(jpContacts);
        jpContacts.setBounds(10, 280, 410, 130);

        jbtUpdate.setText("Update");
        jbtUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtUpdateActionPerformed(evt);
            }
        });
        jpRoute.add(jbtUpdate);
        jbtUpdate.setBounds(780, 400, 73, 23);

        add(jpRoute);
        jpRoute.setBounds(0, 20, 870, 440);

        javax.swing.GroupLayout jpRouteArrowLayout = new javax.swing.GroupLayout(jpRouteArrow);
        jpRouteArrow.setLayout(jpRouteArrowLayout);
        jpRouteArrowLayout.setHorizontalGroup(
            jpRouteArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 150, Short.MAX_VALUE)
        );
        jpRouteArrowLayout.setVerticalGroup(
            jpRouteArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );

        add(jpRouteArrow);
        jpRouteArrow.setBounds(180, 0, 150, 20);
    }// </editor-fold>//GEN-END:initComponents

    private void jbSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSearchActionPerformed
        if(jtfICID.getText().length()!=0){
            if(isNumeric(jtfICID.getText())){
                if(jcbID.isSelected()){
                    String staffInfo = RestServer.httpGet("searchStaffById", ""+jtfICID.getText());
                     
                    try{
                        JSONObject json = new JSONObject(staffInfo);
                        JSONObject content = json.getJSONObject("content");

                        if(jtfICID.getText().length()!=0){
                            jtfFirstName.setText(content.getString("firstname"));
                            jtfLastName.setText(content.getString("lastname"));
                            try{
                                Date result =  df.parse(content.getString("dob"));
                                jtfDoB.setDate(result);
                            }catch(ParseException ex){
                                Toast.makeText(getParent(), ""+ex, Toast.LENGTH_LONG).display();
                            }
                            if(content.getString("gender").equals("M")){
                                jrbMale.setSelected(true);
                            }else{
                                jrbFemale.setSelected(false);
                            }

                            jlblImage.setIcon(this.getImageFile(content.getString("profilePicture"), true));
                            
                            for(int i =0 ; i<jcbPosition.getItemCount();i++){
                                if(content.getString("position").equals(jcbPosition.getItemAt(i))){
                                    jcbPosition.setSelectedIndex(i);
                                }
                            }

                            for(int i =0 ; i<jcbQuestion.getItemCount();i++){
                                if(content.getString("question").equals(jcbQuestion.getItemAt(i))){
                                    jcbQuestion.setSelectedIndex(i);
                                }
                            }
                            jYearEmployedChooser.setYear(content.getInt("yearEmployed"));
                            jtfPhoneNo.setText(content.getString("contactNo"));
                            jtfEmail.setText(content.getString("email"));
                            jtfAddress.setText(content.getString("address"));
                            jtfCity.setText(content.getString("city"));
                            jtfState.setText(content.getString("state"));
                            jtfPostalCode.setText(content.getString("postalCode"));
                            jtfAnswer.setText(content.getString("answer"));
                            enableAll();
                            Toast.makeText(getParent(), "Found!", Toast.LENGTH_LONG).display();
                        }else{
                            disableAll();
                            setDefault();
                            Toast.makeText(getParent(), "Staff ID does not exist in database", Toast.LENGTH_LONG).display();
                        }
                    }catch(JSONException ex){
                        Toast.makeText(getParent(), "Staff not found", Toast.LENGTH_LONG).display();
                        disableAll();
                        setDefault();
                    }
                }else if(jcbIC.isSelected()){
                    if(jtfICID.getText().length()==12){
                        String staffInfo = RestServer.httpGet("searchStaffByIc", ""+jtfICID.getText());
                        try{
                            JSONObject json = new JSONObject(staffInfo);
                            JSONObject content = json.getJSONObject("content");
                            
                            if(jtfICID.getText().length()!=0){
                                jtfFirstName.setText(content.getString("firstname"));
                                jtfLastName.setText(content.getString("lastname"));
                                try{
                                    Date result =  df.parse(content.getString("dob"));
                                    jtfDoB.setDate(result);
                                }catch(ParseException ex){
                                    Toast.makeText(getParent(), ""+ex, Toast.LENGTH_LONG).display();
                                }
                                
                                if(content.getString("gender").equals("M")){
                                    jrbMale.setSelected(true);
                                }else{
                                    jrbFemale.setSelected(false);
                                }

                                for(int i =0 ; i<jcbPosition.getItemCount();i++){
                                    if(content.getString("position").equals(jcbPosition.getItemAt(i))){
                                        jcbPosition.setSelectedIndex(i);
                                    }
                                }

                                for(int i =0 ; i<jcbQuestion.getItemCount();i++){
                                    if(content.getString("question").equals(jcbQuestion.getItemAt(i))){
                                        jcbQuestion.setSelectedIndex(i);
                                    }
                                }
                                jYearEmployedChooser.setYear(content.getInt("yearEmployed"));
                                jtfPhoneNo.setText(content.getString("contactNo"));
                                jtfEmail.setText(content.getString("email"));
                                jtfAddress.setText(content.getString("address"));
                                jtfCity.setText(content.getString("city"));
                                jtfState.setText(content.getString("state"));
                                jtfPostalCode.setText(content.getString("postalCode"));
                                jtfAnswer.setText(content.getString("answer"));
                                enableAll();
                                Toast.makeText(getParent(), "Found!", Toast.LENGTH_LONG).display();
                            }else{
                                disableAll();
                                setDefault();
                                Toast.makeText(getParent(), "Staff IC does not exist in database", Toast.LENGTH_LONG).display();
                            }
                        }catch(JSONException ex){
                            Toast.makeText(getParent(), "Staff ID not exist", Toast.LENGTH_LONG).display();
                            disableAll();
                            setDefault();
                        }
                    }else{
                        Toast.makeText(getParent(), "IC must be 12 numeric characters!", Toast.LENGTH_LONG).display();
                    }
                }
            }else{
                Toast.makeText(getParent(), "The ID or IC must be numeric!", Toast.LENGTH_LONG).display();
            }
        }else{
            Toast.makeText(getParent(), "Please input IC or ID to search!", Toast.LENGTH_LONG).display();
        }
    }//GEN-LAST:event_jbSearchActionPerformed

    private void jcbICActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbICActionPerformed
        jtfICID.setText(null);
        setDefault();
        disableAll();
    }//GEN-LAST:event_jcbICActionPerformed

    private void jcbIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbIDActionPerformed
        jtfICID.setText(null);
        setDefault();
        disableAll();
    }//GEN-LAST:event_jcbIDActionPerformed

    private Map<String, Object> getAllInputData(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dateOfBirth = jtfDoB.getDate();
        String dob = format.format(dateOfBirth);

        data.put("firstname",jtfFirstName.getText());
        data.put("lastname", jtfLastName.getText());
        data.put("dob",dob);
        Toast.makeText(getParent(), ""+jtfDoB.getDate(), Toast.LENGTH_LONG).display();
        if(jrbMale.isSelected()){
            data.put("gender","M");
        }else{
            data.put("gender","F");
        }
        data.put("position",jcbPosition.getSelectedItem().toString());
        data.put("yearEmployed", jYearEmployedChooser.getYear());
        data.put("status","Available");
        
        data.put("address", jtfAddress.getText());
        data.put("city", jtfCity.getText());
        data.put("state", jtfState.getText());
        data.put("postalCode", jtfPostalCode.getText());
        data.put("contactNo", jtfPhoneNo.getText());
        data.put("email", jtfEmail.getText());
        data.put("question", jcbQuestion.getSelectedItem().toString());
        data.put("answer", jtfAnswer.getText());
        return data;
    }
    
    private void jYearEmployedChooserMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jYearEmployedChooserMousePressed

    }//GEN-LAST:event_jYearEmployedChooserMousePressed

    private void jYearEmployedChooserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jYearEmployedChooserMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jYearEmployedChooserMouseClicked

    private void jbtUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtUpdateActionPerformed
        Pattern patternFirstName = Pattern.compile("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$");
        Matcher matcherFirstName = patternFirstName.matcher(jtfFirstName.getText());
        boolean matchFirstName = matcherFirstName .matches();
        
        Pattern patternLastName = Pattern.compile("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$");
        Matcher matcherLastName = patternLastName.matcher(jtfLastName.getText());
        boolean matchLastName = matcherLastName .matches();
        
        Pattern patternEmail = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher matcherEmail = patternEmail.matcher(jtfEmail.getText());
        boolean matchEmail = matcherEmail.matches();
        
        Pattern patternPhone = Pattern.compile("\\d{3}-\\d{7}");
        Matcher matcherPhone = patternPhone.matcher(jtfPhoneNo.getText());
        boolean matchPhone = matcherPhone.matches();

        Pattern patternCity = Pattern.compile("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$");
        Matcher matcherCity = patternCity.matcher(jtfCity.getText());
        boolean matchCity = matcherCity.matches();

        Pattern patternState = Pattern.compile("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$");
        Matcher matcherState = patternState.matcher(jtfState.getText());
        boolean matchState = matcherState.matches();
        
        StringBuilder errors = new StringBuilder("Errors :\n");
        boolean validate = true;
        
        if(jtfFirstName.getText().length()==0){
            errors.append("First Name cannot be empty\n");
            validate = false;
        }else if(matchFirstName){
        }else if(!matchFirstName){
            errors.append("First Name cannot contain numeric characters\n");
            validate = false;
        }       
        
            
        if(jtfLastName.getText().length()==0){
            errors.append("Last Name cannot be empty\n");
            validate = false;
        }else if(matchLastName){
        }else if(!matchLastName){
            errors.append("Last Name cannot contain numeric characters\n");
            validate = false;
        }
        
        if(jtfPhoneNo.getText().length()==0){
            errors.append("Phone number cannot be empty\n");
            validate = false;
        }else if(matchPhone){
        }else if(!matchPhone){
            errors.append("Phone format is invalid  E.g. XXX-XXXXXXX\n");
            validate = false;
        }
        
        if(jtfEmail.getText().length()==0){
            errors.append("Email cannot be empty\n");
            validate = false;
        }else if(isValidEmailAddress(jtfEmail.getText())){
        }else{
            errors.append("Email format is invalid  E.g. name@email.com\n");
            validate = false;
        }
        
        if(jtfAddress.getText().length()==0){
            errors.append("Address cannot be empty\n");
            validate = false;
        }
        
        if(jtfCity.getText().length()==0){
            errors.append("City cannot be empty\n");
            validate = false;
        }else if(matchCity){
        }else{
            errors.append("City can only contains alphabets\n");
            validate = false;
        }
        
        if(jtfState.getText().length()==0){
            errors.append("State cannot be empty\n");
            validate = false;
        }else if(matchState){
        }else{
            errors.append("State can only contains alphabets\n");
            validate = false;
        }
        
        if(jtfPostalCode.getText().length()==0){
            errors.append("Postal Code cannot be empty\n");
        }else if(isNumeric(jtfPostalCode.getText()) &&  jtfPostalCode.getText().length()==5){
        }else{
            errors.append("Postal Code can only be numeric and contains 5 digits E.g. 53300\n");
            validate = false;
        }
        
        if(jtfAnswer.getText().length()==0){
            errors.append("Answer cannot be empty\n");
            validate = false;
        }
        
        if(!isNumeric(""+jYearEmployedChooser.getYear())){
            errors.append("Employed Year must be digit");
            validate = false;
        }

        if(validate){
            if(jcbID.isSelected()){
                String b = RestServer.httpPut("updateStaffById",getAllInputData() ,jtfICID.getText());
                try{
                    JSONObject json = new JSONObject(b);
                    System.out.println(json);
                    Toast.makeText(getParent(), "Staff has been successfully updated", Toast.LENGTH_LONG).display();
                }catch (JSONException ex) {
                    Toast.makeText(getParent(), "Staff does not exist\n Please check the Id again\nB:", Toast.LENGTH_LONG).display();
                    System.out.println(ex);
                    setDefault();
                    disableAll();
                }
            }else if(jcbIC.isSelected()){
                String b = RestServer.httpPut("updateStaffByIc",getAllInputData() ,jtfICID.getText());
                try{
                    JSONObject json = new JSONObject(b);
                    Toast.makeText(getParent(), "Staff has been successfully updated", Toast.LENGTH_LONG).display();
                }catch (JSONException ex) {
                    Toast.makeText(getParent(), "Staff does not exist\n Please check the Ic again", Toast.LENGTH_LONG).display();
                    setDefault();
                    disableAll();
                }
            }
        }else{
            Toast.makeText(getParent(), ""+errors, Toast.LENGTH_LONG).display();
        }
    }//GEN-LAST:event_jbtUpdateActionPerformed

    private void jbtBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBrowseActionPerformed
        chooser =   new JFileChooser();
        filter = new FileNameExtensionFilter("jpeg, gif and png files", "jpg", "gif", "png");
        chooser.addChoosableFileFilter(filter);
        int i = chooser.showOpenDialog(jlblImage);
        if(i==JFileChooser.APPROVE_OPTION)
        {
            image = chooser.getSelectedFile();
            photo   =   new ImageIcon(image.getAbsolutePath());
            scaleImage = photo.getImage().getScaledInstance(91, 91, Image.SCALE_DEFAULT);
            jlblImage.setIcon(new ImageIcon(scaleImage));
            generateByteDataFromImageFile(chooser.getSelectedFile());
        }
    }//GEN-LAST:event_jbtBrowseActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgGender;
    private javax.swing.ButtonGroup bgIndex;
    private javax.swing.JLabel jLabel3;
    private com.toedter.calendar.JYearChooser jYearEmployedChooser;
    private javax.swing.JButton jbSearch;
    private javax.swing.JButton jbtBrowse;
    private javax.swing.JButton jbtUpdate;
    private javax.swing.JCheckBox jcbIC;
    private javax.swing.JCheckBox jcbID;
    private javax.swing.JComboBox jcbPosition;
    private javax.swing.JComboBox jcbQuestion;
    private javax.swing.JLabel jlblAddress;
    private javax.swing.JLabel jlblAnswer;
    private javax.swing.JLabel jlblCity;
    private javax.swing.JLabel jlblDoB;
    private javax.swing.JLabel jlblEmail;
    private javax.swing.JLabel jlblFirstName;
    private javax.swing.JLabel jlblGender;
    private javax.swing.JLabel jlblImage;
    private javax.swing.JLabel jlblLastName;
    private javax.swing.JLabel jlblPhoneNo;
    private javax.swing.JLabel jlblPosition;
    private javax.swing.JLabel jlblPostalCode;
    private javax.swing.JLabel jlblQuestion;
    private javax.swing.JLabel jlblState;
    private javax.swing.JLabel jlblYearEmployed;
    private javax.swing.JPanel jpAddress;
    private javax.swing.JPanel jpContacts;
    private javax.swing.JPanel jpRoute;
    private javax.swing.JPanel jpRouteArrow;
    private javax.swing.JPanel jpSecurity;
    private javax.swing.JPanel jpStaffParticular;
    private javax.swing.JRadioButton jrbFemale;
    private javax.swing.JRadioButton jrbMale;
    private javax.swing.JTextField jtfAddress;
    private javax.swing.JTextField jtfAnswer;
    private javax.swing.JTextField jtfCity;
    private com.toedter.calendar.JDateChooser jtfDoB;
    private javax.swing.JTextField jtfEmail;
    private javax.swing.JTextField jtfFirstName;
    private javax.swing.JTextField jtfICID;
    private javax.swing.JTextField jtfLastName;
    private javax.swing.JTextField jtfPhoneNo;
    private javax.swing.JTextField jtfPostalCode;
    private javax.swing.JTextField jtfState;
    // End of variables declaration//GEN-END:variables
}
